package com.lianzai.car.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.lianzai.common.controller.BaseController;
import com.lianzai.mobile.domain.CarPriceRuleDO;
import com.lianzai.mobile.service.CarPriceRuleService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.lianzai.common.utils.PageUtils;
import com.lianzai.common.utils.Query;
import com.lianzai.common.utils.R;

import javax.servlet.http.HttpServletRequest;

/**
 * 金额规则表
 * 
 * @author zb
 * @email 1106900429@qq.com
 * @date 2018-12-31 22:12:32
 */
 
@Controller
@RequestMapping("/car/carPriceRule")
public class CarPriceRuleController extends BaseController{
	@Autowired
	private CarPriceRuleService carPriceRuleService;
	
	@GetMapping()
	@RequiresPermissions("car:carPriceRule:carPriceRule")
	String CarPriceRule(){
	    return "car/carPriceRule/carPriceRule";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("car:carPriceRule:carPriceRule")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		List<CarPriceRuleDO> carPriceRuleList = carPriceRuleService.list(query);
		for(int i=0;i<carPriceRuleList.size();i++){
            CarPriceRuleDO cpdo =new CarPriceRuleDO();
            cpdo = carPriceRuleList.get(i);
            if(4 == cpdo.getType()){
                List<Map> segList = carPriceRuleService.getSegInfo(cpdo.getId());
                String segMsg = "";
                String freeHour = "-1";
                for(int j=0;j<segList.size();j++){
                    String start = String.valueOf(segList.get(j).get("start"));
                    String end = String.valueOf(segList.get(j).get("end"));
                    String cash = String.valueOf(segList.get(j).get("cash"));
                    if("".equals(segMsg)){
                     	if("0".equals(cash) || "0.00".equals(cash)){
							freeHour = end;
							end = (int)Math.floor(Double.parseDouble(end)*60)+"";
							segMsg = "【<span style='color:Red'>免费时长"+end+"分钟</span>】";
						}else{
							segMsg = "【"+(int)Double.parseDouble(start)+"小时-"+(int)Double.parseDouble(end)+"小时】收费"+cash +"元";
						}
                    }else{
						if(freeHour.equals(start)){
							start = (int)Math.floor(Double.parseDouble(freeHour)*60)+"";
							segMsg = segMsg + "<br>【"+start+"分钟-"+Double.parseDouble(end)+"小时】收费"+cash +"元";
						}else{
							segMsg = segMsg + "<br>【"+(int)Double.parseDouble(start)+"小时-"+(int)Double.parseDouble(end)+"小时】收费"+cash +"元";
						}

                    }
                }
                cpdo.setSegMsg(segMsg);
            }
        }
		int total = carPriceRuleService.count(query);
		PageUtils pageUtils = new PageUtils(carPriceRuleList, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("car:carPriceRule:add")
	String add(){
	    return "car/carPriceRule/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("car:carPriceRule:edit")
	String edit(@PathVariable("id") Long id,Model model){
		CarPriceRuleDO carPriceRule = carPriceRuleService.get(id);
        List<Map> segList = carPriceRuleService.getSegInfo(id);
		model.addAttribute("carPriceRule", carPriceRule);
        model.addAttribute("segList", segList);
		for(int j=0;j<segList.size();j++){
			String cash = String.valueOf(segList.get(j).get("cash"));
			String end = String.valueOf(segList.get(j).get("end"));
			if("0".equals(cash) || "0.00".equals(cash)){
				model.addAttribute("freeMin", (int)Math.floor(Double.parseDouble(end)*60)+"");
			}
		}
	    return "car/carPriceRule/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("car:carPriceRule:add")
	public R save( CarPriceRuleDO carPriceRule){
		carPriceRule.setCreateId(getUserId());
		if(carPriceRuleService.save(carPriceRule)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("car:carPriceRule:edit")
	public R update( CarPriceRuleDO carPriceRule){
		carPriceRuleService.update(carPriceRule);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	public R remove( Long id,Integer type){
		//校验是否有小区绑定，如果有则不能删除
		Map params = new HashedMap();
		params.put("ruleid",id);
		params.put("type",type);
        List<Map> ruleCommunityList = carPriceRuleService.queryRuleCommunityList(params);
        if(ruleCommunityList != null && ruleCommunityList.size() > 0){
			return R.error(110,"无法删除，有小区绑定了此规则");
		}else{
			if(carPriceRuleService.remove(id)>0){
				return R.ok();
			}
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("car:carPriceRule:batchRemove")
	public R remove(@RequestParam("ids[]") Long[] ids){
		carPriceRuleService.batchRemove(ids);
		return R.ok();
	}

	/**
	 * 保存临时
	 */
	@ResponseBody
	@RequestMapping("/saveLs")
	@RequiresPermissions("car:carPriceRule:add")
	public R saveLs(HttpServletRequest request,@RequestBody JSONObject obj){
		String amt  = obj.getString("amt");//request.getParameter("amt");
		String ruleName  = obj.getString("ruleName");//request.getParameter("ruleName");
        //获取时段列表
        List<Map> segTimeList = (List<Map>)obj.get("segList");

		long userId = getUserId();
		Map map = new HashedMap();
		map.put("type","4");
		map.put("createId",userId);
		map.put("amt",0);
        map.put("ruleName",ruleName);

        int result = carPriceRuleService.saveLs(map);
		if(result>0){
		    String ruleId = String.valueOf(map.get("id"));
		    for(int i=0;i<segTimeList.size();i++){
		        Map t_map = segTimeList.get(i);
                t_map.put("ruleId",ruleId);
                carPriceRuleService.saveLsSegRule(t_map);
            }
			return R.ok();
		}
		return R.error();
	}

	@ResponseBody
	@RequestMapping("/updateLs")
	@RequiresPermissions("car:carPriceRule:edit")
	public R updateLs( HttpServletRequest request,@RequestBody JSONObject obj){
        long id  = Long.parseLong(obj.getString("id"));//request.getParameter("amt");
        String amt  = obj.getString("amt");//request.getParameter("amt");
        String ruleName  = obj.getString("ruleName");//request.getParameter("ruleName");
        //获取时段列表
        List<Map> segTimeList = (List<Map>)obj.get("segList");

        long userId = getUserId();
        CarPriceRuleDO carPriceRule = new CarPriceRuleDO();
        carPriceRule.setAmt(BigDecimal.valueOf(Long.parseLong(amt)));
        carPriceRule.setId(id);
        carPriceRule.setCreateId(userId);
        carPriceRule.setRuleName(ruleName);
        carPriceRule.setType(4);
        carPriceRuleService.updateLs(carPriceRule);
        //时段关联先干掉，然后重新插入
        int result = carPriceRuleService.removeSegInfo(id);
        if(result>0){
            for(int i=0;i<segTimeList.size();i++){
                Map t_map = segTimeList.get(i);
                t_map.put("ruleId",id);
                carPriceRuleService.saveLsSegRule(t_map);
            }
            return R.ok();
        }

		return R.ok();
	}

	/**
	 * 绑定规则
	 */
	@PostMapping( "/bind")
	@ResponseBody
	public R bind( Long ruleID,Long id,Integer type){
		if(carPriceRuleService.bind(id,ruleID,type)>0){
			return R.ok();
		}
		return R.error();
	}
}
